/*
 * Copyright 2014 Semidata. All rights reserved.
 */
package com.semidata.rtd.engine.job;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author shewei@semidata.com, She Wei
 * 
 */
public abstract class AsyncTask extends AbstractTask {

	private Exception cause;
	private AtomicBoolean isDone;

	public AsyncTask(Job job, long timeout) {
		super(job, timeout);
		this.cause = null;
		this.isDone = new AtomicBoolean(false);
	}

	@Override
	public void afterExecution(Exception cause) {
		if (cause != null)
			done(cause);
	}

	@Override
	public Exception getException() {
		return cause;
	}

	public void done() {
		done(null);
	}

	public void done(Exception cause) {

		if (isDone.compareAndSet(false, true)) {
			this.cause = cause;
			getJob().taskComplete(this);
		}

	}

}
